from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
import uuid

app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route('/api/sub', methods=['POST'])
def submit_form_data():
    data = request.get_json()
    test = data.get('test')
    test2 = data.get('test2')
    user_uuid = uuid.uuid4()
    print("已连接后端")
    db_config = {
        'host': '110.41.147.241',
        'user': 'test_ai',
        'password': 'nHB3cbLDzAeH74eR',
        'database': 'ai_sql',
        }
    connection = pymysql.connect(**db_config)
    try:
        cursor = connection.cursor()
        sql ="INSERT INTO orderInfo (order_on, user_subject, user_title) VALUES (%s, %s, %s)"
        values = ({user_uuid},{test},{test2})
        if values:
            cursor.execute(sql, values)
            connection.commit()
            print("数据插入成功!")
            connection.close()
        else:
            print("执行数据库操作时出错:")
            connection.close()

    finally:
        print("执行已完成")
    
    result = f"Received data: test={test}, test2={test2}"
    return jsonify({'code': 200, 'message': 'success', 'result': result, 'uuid' : user_uuid})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 6851)
